﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Web.Models;

namespace Web.Controllers
{
    public class AccountController : Controller
    {
        //
        // GET: /Account/

        public ActionResult Index()
        {
            return View("Login");
        }


        public ActionResult Login()
        {
            // 1.获取表单信息
            string LoginId = this.Request.Form["LoginId"];
            string LoginPwd = this.Request.Form["LoginPwd"];
            // 2.进行非空验证
            if (string.IsNullOrEmpty(LoginId))
            {
                return View();
            }
            if (string.IsNullOrEmpty(LoginPwd))
            {
                return View();
            }
            // 3.对数据进行封装
            User user = new User { LoginId = LoginId, LoginPwd = LoginPwd };
 
            // 4.对数据进行业务处理（存不存在该用户）
            if (Login(user)) {
                string RecordMe = this.Request.Form["RecordMe"];
                if (string.IsNullOrEmpty(RecordMe))
                {
                    Response.Cookies["loginId"].Expires = DateTime.Now.AddDays(-1);
                    Response.Cookies["loginPwd"].Expires = DateTime.Now.AddDays(-1);
                }
                else
                {
                    HttpCookie loginIdCookie = new HttpCookie("loginId", LoginId);
                    loginIdCookie.Expires = DateTime.MaxValue;
                    Response.Cookies.Add(loginIdCookie);
                    HttpCookie loginPwdCookie = new HttpCookie("loginPwd", LoginPwd);
                    loginPwdCookie.Expires = DateTime.MaxValue;
                    Response.Cookies.Add(loginPwdCookie);
                }
                Session["CurrentUser"] = new User { LoginId = LoginId };

                Response.Redirect("~/Home/Index");
            }

            return View();
        }

        public void Logout()
        {
            Session.Abandon();
            Response.Redirect("~/Home/Index");
        }

        private bool Login(User user)
        {
            if (user.LoginId == "admin" && user.LoginPwd == "123")
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }
}
